package com.cogent.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.log4j.Logger;

import com.cogent.common.exception.SystemRuntimeException;

/**
 * 字符串转换处理类。</br>
 * 提供将字符串转换为日期，数字，布尔等类型。
 * @author daiys 
 * @version 1.0<br/>
 * ****************************************************<br/>
 * 版本号	 修改日期		作者			更改原因<br/>
 * 1.0		2009-11-24	daiys		新增<br/>
 * ****************************************************<br/>
 */
public class StringUtil {
	private static Logger _log = Logger.getLogger(StringUtil.class); 
	public final static String STRING_LINK_SYMBOL = "+";

	/**
	 * 判断字符串是否为空，为NULL
	 * @param str 传入的字符串
	 * @return true为空或为null；false非空
	 */
	public static final boolean isEmpty(String str) {
		if((str == null) || (str.length() == 0))
			return true;
		return false;
	}
	
	/**
	 * 将传入字符串转换为int
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回0
	 */
	public static final int toInt(String str) {
		return toInt(str, 0);
	}
	
	public static final int toInt(String str, int defvalue) {
		if(isEmpty(str))
			return defvalue;
		else
			return Integer.parseInt(str);
	}
	
	/**
	 * 将传入字符串转换为Integer
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回null
	 */
	public static final Integer toIngeger(String str) {
		if(isEmpty(str))
			return null;
		else
			return new Integer(str);
	}
	
	/**
	 * 将传入字符串转换为double
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回0d
	 */
	public static final double toDouble(String str) {
		if(isEmpty(str))
			return 0d;
		else
			return Double.parseDouble(str);
	}
	
	/**
	 * 将传入字符串转换为Double
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回null
	 */
	public static final Double toComplexDouble(String str) {
		if(isEmpty(str))
			return null;
		else
			return new Double(str);
	}
	
	/**
	 * 将传入字符串转换为float
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回0f
	 */
	public static final float toFloat(String str) {
		if(isEmpty(str))
			return 0f;
		else
			return Float.parseFloat(str);
	}
	
	/**
	 * 将传入字符串转换为Float
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回null
	 */
	public static final Float toComplexFloat(String str) {
		if(isEmpty(str))
			return null;
		else
			return new Float(str);
	}	
	
	/**
	 * 将传入字符串转换为boolean
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回false;
	 * 字符串不区分大小写为true,1时返回true,反之返回false;
	 */
	public static final boolean toBoolean(String str) {
		boolean flag = false;
		if(! isEmpty(str)) {
			if(str.equalsIgnoreCase("true") || str.equals("1"))
				flag =true;
			else
				flag = false;
		}
		
		return flag;
	}
	
	/**
	 * 将传入字符串转换为boolean,为空时转换为默认值
	 * @param str 待转换的字符串
	 * @param flag 为空时返回值
	 * @return 字符串为空或null时返回flag传入的值;
	 * 字符串不区分大小写为true,1时返回true,反之返回false;
	 */
	public static final boolean toBooleanDefault(String str, boolean flag) {
		boolean ret = false;
		if(isEmpty(str))
			ret = flag;
		else {
			if(str.equalsIgnoreCase("true") || str.equals("1"))
				ret =true;
			else
				ret = false;
		}
		
		return ret;
	}
	
	/**
	 * 将传入字符串转换为Boolean
	 * @param str 待转换的字符串
	 * @return 字符串为空或null时返回null;
	 * 字符串不区分大小写为true,1时返回true,反之返回false;
	 */
	public static final Boolean toComplexBoolean(String str) {
		Boolean flag = null;
		if(! isEmpty(str)) {
			if(str.equalsIgnoreCase("true") || str.equals("1"))
				flag = new Boolean("true");
			else
				flag = new Boolean("false");
		}
		
		return flag;
	}	
	
	// 压缩   
    public static String compress(String str){   
        if (str == null || str.length() == 0) {   
            return str;   
        }
        try{
	        ByteArrayOutputStream out = new ByteArrayOutputStream();   
	        GZIPOutputStream gzip = new GZIPOutputStream(out);   
	        gzip.write(str.getBytes());   
	        gzip.close();   
	        return out.toString("ISO-8859-1"); 
        }catch(Throwable t) {
        	throw new SystemRuntimeException(SystemRuntimeException.HIGH, t, "err.msg.system");
        }
    }   
    
    //解压缩   
    public static String decompress(String str) {   
        if (str == null || str.length() == 0) {   
            return str;   
        }  
        try{
	        ByteArrayOutputStream out = new ByteArrayOutputStream();   
	        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));   
	        GZIPInputStream gunzip = new GZIPInputStream(in);   
	        byte[] buffer = new byte[256];   
	        int n;   
	        while ((n = gunzip.read(buffer)) >= 0) {   
	            out.write(buffer, 0, n);   
	        }   
	        return out.toString("ISO-8859-1"); 
        }catch(Throwable t) {
        	throw new SystemRuntimeException(SystemRuntimeException.HIGH, t, "err.msg.system");
        }
    }
    
    public static final String encodeHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;

        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString();
    }
    
    public static final String subString(String str, int maxlen, String fix) {
    	String ret = str;
    	if(str.length() > maxlen)
    		ret = str.substring(0, maxlen-1) + fix;
    	
    	return ret;
    }
    
    public static final String getLinkString(String st1, String st2) {
    	return st1 + STRING_LINK_SYMBOL + st2;
    }
    
    public static final boolean isConatianChinese(String str) {
    	Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
    	Matcher matcher = pattern.matcher(str);
    	
    	return matcher.find();
    }
    
    public static final byte[] getByteEncode(String str, String encode) {
    	byte[] ret = str.getBytes();
    	try {
			ret = str.getBytes(encode);
		} catch (UnsupportedEncodingException e) {
			_log.error("+++转换++" + str + "+++为++" + encode + "+++发送错误+++" + e);
		}
    	
    	return ret;
    }
    
    public static final String[] getLinkStrSpan(String str) {
    	return str.split("\\" + STRING_LINK_SYMBOL);
    }
    
    public static String doubleToString(double price) {
		DecimalFormat df = new DecimalFormat("0.00");  
		String num = df.format(price); 

		return num;
	}
    //转义图片地址中的"\"字符
    public static String getPicString(String picurl){
    	StringBuffer buf=new StringBuffer();
	    for(int i=0;i<picurl.length();i++){
	    if((byte)picurl.charAt(i)!=92)
	    	buf.append(picurl.charAt(i));
	    else
	    	buf.append("/");
	    }
	    return buf.toString();
    }
}
